<?php
namespace app\common\model;

use think\Model;

/**
 * 渠道统计模型
 * 存储渠道统计数据
 */
class ChannelStats extends Model
{
    /**
     * 数据表名
     */
    protected $table = 'gf_channel_stats';
    
    /**
     * 主键
     */
    protected $pk = 'id';
    
    /**
     * 自动时间戳
     */
    protected $autoWriteTimestamp = true;
    
    /**
     * 创建时间字段
     */
    protected $createTime = 'created_at';
    
    /**
     * 更新时间字段
     */
    protected $updateTime = 'updated_at';
    
    /**
     * 字段信息
     */
    protected $schema = [
        'id' => 'int',
        'appkey' => 'string',
        'channel' => 'string',
        'stat_date' => 'date',
        'clicks' => 'int',
        'installs' => 'int',
        'events' => 'json',
        'created_at' => 'datetime',
        'updated_at' => 'datetime'
    ];
    
    /**
     * 获取渠道统计
     */
    public function getByChannelAndDate($appkey, $channel, $date)
    {
        return $this->where([
            'appkey' => $appkey,
            'channel' => $channel,
            'stat_date' => $date
        ])->find();
    }
    
    /**
     * 获取应用统计
     */
    public function getByAppkey($appkey, $startDate = null, $endDate = null)
    {
        $query = $this->where('appkey', $appkey);
        
        if ($startDate) {
            $query->where('stat_date', '>=', $startDate);
        }
        
        if ($endDate) {
            $query->where('stat_date', '<=', $endDate);
        }
        
        return $query->order('stat_date', 'desc')->select();
    }
    
    /**
     * 获取渠道统计
     */
    public function getByChannel($appkey, $channel, $startDate = null, $endDate = null)
    {
        $query = $this->where([
            'appkey' => $appkey,
            'channel' => $channel
        ]);
        
        if ($startDate) {
            $query->where('stat_date', '>=', $startDate);
        }
        
        if ($endDate) {
            $query->where('stat_date', '<=', $endDate);
        }
        
        return $query->order('stat_date', 'desc')->select();
    }
    
    /**
     * 获取汇总统计
     */
    public function getSummaryStats($appkey, $startDate = null, $endDate = null)
    {
        $query = $this->where('appkey', $appkey);
        
        if ($startDate) {
            $query->where('stat_date', '>=', $startDate);
        }
        
        if ($endDate) {
            $query->where('stat_date', '<=', $endDate);
        }
        
        return $query->field('
                channel,
                SUM(clicks) as total_clicks,
                SUM(installs) as total_installs,
                CASE 
                    WHEN SUM(clicks) > 0 THEN ROUND((SUM(installs) / SUM(clicks)) * 100, 2)
                    ELSE 0
                END as conversion_rate
            ')
            ->group('channel')
            ->order('total_installs', 'desc')
            ->select();
    }
    
    /**
     * 获取趋势数据
     */
    public function getTrendData($appkey, $channel = null, $startDate, $endDate)
    {
        $query = $this->where('appkey', $appkey)
                     ->whereBetween('stat_date', [$startDate, $endDate]);
        
        if ($channel) {
            $query->where('channel', $channel);
        }
        
        return $query->field('
                stat_date as date,
                SUM(clicks) as clicks,
                SUM(installs) as installs,
                CASE 
                    WHEN SUM(clicks) > 0 THEN ROUND((SUM(installs) / SUM(clicks)) * 100, 2)
                    ELSE 0
                END as conversion_rate
            ')
            ->group('stat_date')
            ->order('stat_date', 'asc')
            ->select();
    }
    
    /**
     * 更新统计数据
     */
    public function updateStats($appkey, $channel, $date, $clicks, $installs, $events = null)
    {
        $existing = $this->getByChannelAndDate($appkey, $channel, $date);
        
        if ($existing) {
            $data = [
                'clicks' => $clicks,
                'installs' => $installs,
                'updated_at' => date('Y-m-d H:i:s')
            ];
            
            if ($events !== null) {
                $data['events'] = json_encode($events);
            }
            
            return $existing->save($data);
        } else {
            $data = [
                'appkey' => $appkey,
                'channel' => $channel,
                'stat_date' => $date,
                'clicks' => $clicks,
                'installs' => $installs,
                'created_at' => date('Y-m-d H:i:s'),
                'updated_at' => date('Y-m-d H:i:s')
            ];
            
            if ($events !== null) {
                $data['events'] = json_encode($events);
            }
            
            return $this->insert($data);
        }
    }
    
    /**
     * 批量更新统计数据
     */
    public function batchUpdateStats($statsData)
    {
        $successCount = 0;
        
        foreach ($statsData as $data) {
            $result = $this->updateStats(
                $data['appkey'],
                $data['channel'],
                $data['stat_date'],
                $data['clicks'],
                $data['installs'],
                $data['events'] ?? null
            );
            
            if ($result) {
                $successCount++;
            }
        }
        
        return $successCount;
    }
}